import React, { useEffect, useState } from 'react';
import { Button, message, Tree } from 'antd';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import client from '@/graphql/client';

import { nanoid } from 'nanoid';
import { getOrgan } from '@/graphql/queries';
import { deleteOrgan, adminCreateOrganInfo, updateOrgan } from '@/graphql/mutations';
const { TreeNode } = Tree;

const schoolId = localStorage.getItem('schoolId');
console.log('schoolId', schoolId);

// const treeData = [
//   {
//     value: '一年级',
//     defaultValue: '一年级',
//     key: '0',
//     parentKey: '0',
//     isEditable: false,
//     children: [
//       {
//         value: '1班',
//         key: '1-1',
//         defaultValue: '1班',
//         isEditable: false,
//       },
//       {
//         value: '3班',
//         key: '1-3',
//         defaultValue: '3班',
//         isEditable: false,
//       },
//     ],
//   },
//   {
//     value: '二年级',
//     defaultValue: '二年级',
//     key: '1',
//     parentKey: '0',
//     isEditable: false,
//     children: [
//       {
//         value: '4班',
//         key: '2-1',
//         defaultValue: '4班',
//         isEditable: false,
//       },
//       {
//         value: '222班',
//         key: '2-2',
//         defaultValue: '222班',
//         isEditable: false,
//       },
//     ],
//   },
// ];

const expandedKeyArr = ['0'];
export default function TreeDemo() {
  const [expandedKeys, setExpandedKeys] = useState(expandedKeyArr);
  const [treeData, settreeData] = useState<any>([]);
  const [dataArr, setData] = useState(treeData);

  // console.log('node', dataArr);

  const initFetch = () => {
    // 如果您需要强制 Apollo Client 向服务器发起新的请求并忽略本地缓存，请使用 fetchPolicy 参数并将其设置为 "network-only"
    client
      .query({ query: getOrgan, variables: { id: schoolId }, fetchPolicy: 'network-only' })
      .then((res) => {
        console.log('initFetch', res);
        const node = res.data.node.childOrganList.map((item: any) => {
          return {
            ...item,
            value: item.name,
            defaultValue: item.name,
            key: item.id,
            children: item.childOrganList.map((child: any) => {
              return {
                ...child,
                value: child.name,
                defaultValue: child.name,
                key: child.id,
              };
            }),
          };
        });
        settreeData(node.slice());
        setData(node.slice());
      });
  };
  useEffect(() => {
    initFetch();
  }, []);
  const addYear = () => {
    client
      .mutate({
        mutation: adminCreateOrganInfo,
        variables: {
          input: {
            organList: [
              {
                name: 'default',
                type: 'GRADE',
                rank: 2,
                parent_organ_id: schoolId,
              },
            ],
          },
        },
      })
      .then((res) => {
        console.log(res);
        initFetch();
        message.success('新增成功');
      });
  };
  const onExpand = (expandedKey: any) => {
    //记录折叠的key值
    setExpandedKeys(expandedKey);
  };

  const editNode = (key: any, data: any[]) =>
    data.forEach(
      (item: { key: any; isEditable: boolean; value: any; defaultValue: any; children: any }) => {
        if (item.key === key) {
          item.isEditable = true;
        } else {
          item.isEditable = false;
        }
        item.value = item.defaultValue; // 当某节点处于编辑状态，并改变数据，点击编辑其他节点时，此节点变成不可编辑状态，value 需要回退到 defaultvalue
        if (item.children) {
          editNode(key, item.children);
        }
      },
    );

  const addNode = (key: any, data: any[]) =>
    data.forEach((item: { key: any; children: { value: string; key: string }[] }) => {
      if (item.key === key) {
        if (item.children) {
          item.children.push({
            value: 'default',
            key: nanoid(), // 这个 key 应该是唯一的
          });
        } else {
          item.children = [];
          item.children.push({
            value: 'default',
            key: nanoid(),
          });
        }
        return;
      }
      if (item.children) {
        addNode(key, item.children);
      }
    });

  const changeNode = (key: any, value: any, data: any[]) =>
    data.forEach((item: { key: any; value: any; children: any }) => {
      if (item.key === key) {
        item.value = value;
      }
      if (item.children) {
        changeNode(key, value, item.children);
      }
    });

  const saveNode = (key: any, data: any[]) =>
    data.forEach(
      (item: { key: any; defaultValue: any; value: any; children: any; isEditable: boolean }) => {
        if (item.key === key) {
          item.defaultValue = item.value;
        }
        if (item.children) {
          saveNode(key, item.children);
        }
        item.isEditable = false;
      },
    );

  const closeNode = (key: any, defaultValue: any, data: any[]) =>
    data.forEach((item: { isEditable: boolean; key: any; value: any; children: any }) => {
      item.isEditable = false;
      if (item.key === key) {
        item.value = defaultValue;
      }
      if (item.children) {
        closeNode(key, defaultValue, item.children);
      }
    });

  const deleteNode = (key: any, data: any[]) =>
    data.forEach((item: { key: any; children: any }, index: any) => {
      if (item.key === key) {
        data.splice(index, 1);
        return;
      } else {
        if (item.children) {
          deleteNode(key, item.children);
        }
      }
    });
  const onChange = (e: React.ChangeEvent<HTMLInputElement>, key: any) => {
    changeNode(key, e.target.value, treeData);
    setData(treeData.slice());
  };
  const onEdit = (key: any) => {
    editNode(key, treeData);
    setData(treeData.slice());
  };

  const onSave = (key: any) => {
    let isChild = false;
    let tmp = treeData.find((item: any) => {
      return (
        item.id === key ||
        item.children.find((e: any) => {
          if (e.id === key) {
            isChild = true;
          }
          return e.id === key;
        })
      );
    });
    if (isChild) {
      tmp = tmp.children.find((item: any) => {
        return item.id === key;
      });
    }
    const val = tmp.value;
    console.log(key, tmp, val);
    client
      .mutate({
        mutation: updateOrgan,
        variables: {
          input: {
            id: key,
            name: val,
          },
        },
      })
      .then((res) => {
        console.log(res);
        initFetch();
      });
    // saveNode(key, treeData);
    // setData(treeData.slice());
  };
  const onClose = (key: any, defaultValue: any) => {
    closeNode(key, defaultValue, treeData);
    setData(treeData);
  };
  const onDelete = (key: any) => {
    console.log(key);
    client
      .mutate({
        mutation: deleteOrgan,
        variables: {
          input: {
            is_removed: true,
            id: key,
          },
        },
      })
      .then(async (res) => {
        console.log(res);
        await initFetch();
        deleteNode(key, treeData);
        setData(treeData.slice());
      })
      .catch((e) => {
        console.log(e);
      });
  };
  const onAdd = (key: string) => {
    if (expandedKeys.indexOf(key) === -1) {
      expandedKeyArr.push(key);
    }
    setExpandedKeys(expandedKeyArr.slice());

    addNode(key, treeData);
    //useState里数据务必为immutable （不可赋值的对象），所以必须加上slice()返回一个新的数组对象
    setData(treeData.slice());
    console.log('key', key);

    // initFetch()
    client
      .mutate({
        mutation: adminCreateOrganInfo,
        variables: {
          input: {
            organList: [
              {
                name: 'default',
                type: 'CLASS',
                rank: 1,
                parent_organ_id: key,
              },
            ],
          },
        },
      })
      .then((res) => {
        console.log(res);
        initFetch();
        message.success('新增成功');
      });
  };
  const renderTreeNodes = (data: any[]) => {
    const nodeArr = data.map((item: any) => {
      if (item.isEditable) {
        item.title = (
          <div>
            <input value={item.value || ''} onChange={(e) => onChange(e, item.key)} />

            <CloseOutlined
              style={{ marginLeft: 10 }}
              onClick={() => onClose(item.key, item.defaultValue)}
            />

            <CheckOutlined style={{ marginLeft: 10 }} onClick={() => onSave(item.key)} />
          </div>
        );
      } else {
        item.title = (
          <div>
            <span>{item.value}</span>
            <span>
              <span style={{ marginLeft: 10 }} onClick={() => onEdit(item.key)}>
                编辑
              </span>
              {item.parentKey === '0' ? null : (
                <span style={{ marginLeft: 10 }} onClick={() => onDelete(item.key)}>
                  删除
                </span>
              )}
              <span style={{ marginLeft: 10 }} onClick={() => onAdd(item.key)}>
                新增
              </span>
            </span>
          </div>
        );
      }

      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }

      return <TreeNode title={item.title} key={item.key} />;
    });

    return nodeArr;
  };

  return (
    <div>
      <Button onClick={addYear}>新增年级</Button>
      <Tree expandedKeys={expandedKeys} onExpand={onExpand}>
        {renderTreeNodes(dataArr)}
      </Tree>
    </div>
  );
}
